package com.bdqn.gulimall.member.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdqn.common.utils.OAuth2Utils;
import com.bdqn.common.utils.PageUtils;
import com.bdqn.common.utils.Query;
import com.bdqn.gulimall.member.dao.MemberDao;
import com.bdqn.gulimall.member.entity.MemberEntity;
import com.bdqn.gulimall.member.entity.MemberLevelEntity;
import com.bdqn.gulimall.member.exception.PhoneException;
import com.bdqn.gulimall.member.exception.UserNameExistException;
import com.bdqn.gulimall.member.service.MemberLevelService;
import com.bdqn.gulimall.member.service.MemberService;
import com.bdqn.gulimall.member.vo.MemberLoginVo;
import com.bdqn.gulimall.member.vo.MemberRegistVo;
import com.bdqn.gulimall.member.vo.SocialUser;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Resource
    private MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 注册
     * @param vo
     */
    @Override
    public void regist(MemberRegistVo vo) {
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = new MemberEntity();
        //设置默认等级
        MemberLevelEntity memberDaoDefaultLevel= memberDao.getDefaultLevel();
        memberEntity.setMemberLevelId(memberDaoDefaultLevel.getId());

        //检查用户名与手机号是否唯一性
        checkPhoneUnique(vo.getPhone());
        checkUserNameUnique(vo.getUserName());

        memberEntity.setPhone(vo.getPhone());
        memberEntity.setUsername(vo.getUserName());

        //密码要进行加密处理
        BCryptPasswordEncoder md5Pass = new BCryptPasswordEncoder();
        String md5Pwd = md5Pass.encode(vo.getPassword());
        memberEntity.setPassword(md5Pwd);


        this.baseMapper.insert(memberEntity);
    }

    /**
     * \
     * 检查手机号唯一性
     *
     * @param phone
     * @return
     */
    @Override
    public void checkPhoneUnique(String phone) throws PhoneException {
        MemberDao baseMapper = this.baseMapper;
        Integer phone1 = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("phone", phone));
        if(phone1>0){
            throw new PhoneException();
        }
    }

    /**
     * \
     * 检查用户名唯一性
     *
     * @param serName
     * @return
     */
    @Override
    public void checkUserNameUnique(String serName) throws UserNameExistException {
        MemberDao baseMapper = this.baseMapper;
        Integer usernamecount = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", serName));
        if(usernamecount>0){
            throw new UserNameExistException();
        }
    }

    /**
     * 登录
     * @param vo
     * @return
     */
    @Override
    public MemberEntity login(MemberLoginVo vo) {
        MemberDao baseMapper = this.baseMapper;
        MemberEntity entity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", vo.getLoginacct()).
                or().eq("phone",vo.getLoginacct()));
        if (entity==null){
            //登陆失败
            return null;
        }else{
            String password = entity.getPassword();
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

            //密码匹配
            boolean matches = bCryptPasswordEncoder.matches(vo.getPassword(), password);
            if(matches){
                return entity;
            }else {
                return null;
            }
        }
    }

    /**
     * 社交用户登录
     *
     * @param socialUser
     * @return
     */
    @Override
    public MemberEntity login(SocialUser socialUser)  {
        //登录和注册合并逻辑
        String uid = socialUser.getUId();
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", socialUser.getUId()));
        if(memberEntity!=null){
            //如果数量大于1  说明用户已经注册了
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in());

            memberDao.updateById(update);

            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());
            return memberEntity;
        }else{
            //2、说明没查到，需要自动注册
            MemberEntity regist = new MemberEntity();
            //3.查询当前社交用户的社交账号信息();
            try {
                //返回出来的JSON
                JSONObject giteeUser = OAuth2Utils.getGiteeUser(socialUser.getAccess_token());
                if(giteeUser!=null){
                    regist.setNickname(giteeUser.getString("name"));
                    //因不可检索性别，默认男性
                    regist.setGender(1);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            regist.setSocialUid(socialUser.getUId());
            regist.setAccessToken(socialUser.getAccess_token());
            regist.setExpiresIn(socialUser.getExpires_in());
            memberDao.insert(regist);

            return regist;
        }
    }

}
